const os = require("os");
const fs = require("fs");
const router = require("express").Router();
const { Ajax, enu} = require("../utils/Ajax");

router.post("/status", async (req, res) => {
    const cpuAverage = () => {
        let totalIdle = 0;
        let totalTick = 0;
        let cpus = os.cpus();

        for (let i = 0, len = cpus.length; i < len; i++) {
            let cpu = cpus[i];
            for (let type in cpu.times) {
                totalTick += cpu.times[type];
            }
            totalIdle += cpu.times.idle;
        }

        return { idle: totalIdle / cpus.length, total: totalTick / cpus.length };
    };

    // 获取初始CPU使用率
    const startMeasure = cpuAverage();

    // 设置延迟，以便计算CPU使用率
    setTimeout(() => {
        const endMeasure = cpuAverage();

        // 计算CPU使用率
        const idleDifference = endMeasure.idle - startMeasure.idle;
        const totalDifference = endMeasure.total - startMeasure.total;
        const cpuPercentage = (100 - Math.round(100 * idleDifference / totalDifference));

        // 获取IP地址
        const ip = Object.values(os.networkInterfaces())
            .flat()
            .find((interface) => interface.family === 'IPv4' && !interface.internal)
            ?.address || '未找到IP地址';

        // 获取CPU频率信息
        const cpuSpeeds = os.cpus().map(cpu => cpu.speed);

        // 获取内存信息
        const totalMemory = os.totalmem();
        const freeMemory = os.freemem();
        const usedMemory = totalMemory - freeMemory;


        // 获取服务器运行负载状态
        const loadavg = os.loadavg();

        const systemStatus = {
            serverName: os.hostname(), // 服务器名称
            ip: ip, // 服务器IP地址
            cpu: {
                count: os.cpus().length, // CPU核心总数
                models: os.cpus().map(cpu => cpu.model), // 所有CPU模型的数组
                speeds: cpuSpeeds, // 所有CPU的频率数组
                usage: cpuPercentage // CPU使用率
            },
            memory: {
                total: totalMemory, // 内存总量
                used: usedMemory, // 已用内存量
                free: freeMemory // 可用内存量
            },
            loadavg: loadavg, // 服务器运行负载状态，包含1分钟、5分钟和15分钟内的平均负载
            cpuLoad: os.cpus().map(cpu => { // 每个CPU核心的负载率
                const total = Object.values(cpu.times).reduce((acc, val) => acc + val, 0); // CPU核心的总时间
                const idle = cpu.times.idle; // CPU核心的空闲时间
                return ((total - idle) / total) * 100; // 计算CPU核心的负载率
            })
        };

        res.send(Ajax(enu().code.service.success, enu().msg.service.computer[0], systemStatus));
    }, 1000);
});

module.exports = router;
